Sheffield | 25-SDC-Nov | Sheida Shabankari | Sprint 2 |Implement linked list in python#101
Conversation
| elif self.head==self.tail: | ||
| node_value=self.head.value | ||
| self.head=None | ||
| self.tail=None | ||
| else: | ||
| node_value=self.tail.value | ||
| previous_node=self.tail.previous | ||
| self.tail=previous_node |
There was a problem hiding this comment.
Could also consider calling remove() to remove the tail -- less code to maintain.
| node_to_remove.next=None | ||
| node_to_remove.previous=None |
There was a problem hiding this comment.
Why not also clearing the reference of the removed tail in pop_tail()?
| elif self.head==self.tail: | ||
| node_to_remove = self.head | ||
| node_value = node_to_remove.value | ||
| self.remove(node_to_remove) | ||
|
|
||
| else: | ||
| node_to_remove = self.tail | ||
| node_value = node_to_remove.value | ||
| self.remove(node_to_remove) |
There was a problem hiding this comment.
Wouldn't this work the same as the code on line 34-42?
node_value = self.tail.value
self.remove(self.tail)
There was a problem hiding this comment.
I understand the point now.
remove() handles both single-node and multiple-node cases,
so I simplified pop_tail() to just call remove(self.tail).
This makes the code shorter and cleaner.
|
Just noticed you removed these two lines from Why? |
|
You are right. |
|
I could not find the code for clearing references in |
|
You’re right, that was an oversight on my part. |
|
All good now. Well done. |
This PR implements a doubly linked list in Python with O(1) time complexity for all required operations.
Added a Node class to represent elements with value, next, and previous references.
Implemented push_head to insert elements at the head and return a node handle for constant-time removal.
Implemented pop_tail to remove and return the value of the tail node.
Implemented remove to delete a node from the list using its handle, without traversing the list.
Properly maintains head and tail references and updates links for all edge cases (empty list, single node, head, tail, and middle nodes).
All provided tests pass successfully.